﻿using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PalcoCentral
{
    public partial class pcVerCalend : Form
    {

        List<Library.CalendarioInput> cis;
        string nomeCalend;
        public Dictionary<String, ICollection<Database.person>> listaProfs {get ; set; }
        public Dictionary<String, ICollection<Database.student>> listaStudents { get; set; }

        public pcVerCalend(string nome, string nomeCalend, List<Library.CalendarioInput> cis)
        {
            InitializeComponent();
            this.Text = nome + " - Palco Central [Software de Gestão]";
            this.groupBox1.Text = nomeCalend;
            this.nomeCalend = nomeCalend;
            this.cis = cis;
            this.FormBorderStyle = FormBorderStyle.FixedSingle;

         
            
        }

        public void populateCalend(){
            orderCalendar();
            drawCalen();
            string subPath = "Horarios Imprimidos"; // your code goes here
            String fullPath = Path.GetFullPath(subPath);
            bool isExists = System.IO.Directory.Exists(fullPath);

            if (!isExists)
                System.IO.Directory.CreateDirectory(fullPath);
            printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
        }

        private void orderCalendar()
        {
            List<Library.CalendarioInput> tmpCis = cis; ;
            List<Library.CalendarioInput> orderer = new List<Library.CalendarioInput>();

            while (tmpCis.Count > 0)
            {
                int index = -1;
                TimeSpan tsMin;
                TimeSpan.TryParse("23:59:59", out tsMin);
                for (int i = 0; i < tmpCis.Count; i++)
                {
                    if (cis[i].Start < tsMin)
                    {
                        tsMin = cis[i].Start;
                        index = i;
                    }
                }
                orderer.Add(tmpCis[index]);
                tmpCis.Remove(tmpCis[index]);
            }
            cis = orderer;
        }



        DataTable dt;
        private void drawCalen()
        {
            GridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            DataRow dr;
            dt = new DataTable();
            
            dt.Columns.Add("Horas");
            dt.Columns.Add("Segunda");
            dt.Columns.Add("Terça");
            dt.Columns.Add("Quarta");
            dt.Columns.Add("Quinta");
            dt.Columns.Add("Sexta");
            dt.Columns.Add("Sábado");
            //dt.DefaultView.Sort = "Horas asc";
            for (int i = 0; i < cis.Count; i++)
            {
                dr = null;
                  int j = 0;
                string horas =  (cis[i].Start + "h" + " - " + cis[i].End + "h").Replace(":00h", "");
              
                  foreach (DataRow r in dt.Rows)
                  {
                      if (r[0].ToString().CompareTo(horas) == 0)
                      {
                         
                          dr = dt.Rows[j];
                          
                         // return;
                          //dt.Rows.Add(dr);
                      }
                      j++;
                  }
                  int contador = 0;
                  if (dr == null)
                  {
                       dr = dt.NewRow();
                      dr["Horas"] = horas;
                      string tmp = cis[i].Nome;
                      if (listaProfs != null)
                      {
                          ICollection<Database.person> val = listaProfs[cis[i].Nome];
                          IEnumerator<Database.person> e1 = val.GetEnumerator();
                          while (e1.MoveNext())
                          {
                              tmp += " \nProf. " + name(e1.Current.personName);
                          }
                      }
                      else if (listaStudents != null)
                      {
                          ICollection<Database.student> val = listaStudents[cis[i].Nome];
                          IEnumerator<Database.student> e1 = val.GetEnumerator();
                          while (e1.MoveNext())
                          {
                              tmp += " \n" + (++contador) + "." + name(e1.Current.person.personName);
                          }
                      }
                      dr[cis[i].DayOfWeek] = tmp;

                      dt.Rows.Add(dr);
                      
                  }
                  else
                  {
                      //dt.Rows.Remove(dr);
                      dr["Horas"] = horas;
                      string tmp = cis[i].Nome;
                      if (listaProfs != null)
                      {
                          ICollection<Database.person> val = listaProfs[cis[i].Nome];
                          IEnumerator<Database.person> e1 = val.GetEnumerator();
                          while (e1.MoveNext())
                          {
                              tmp += " \nProf. " + name(e1.Current.personName);
                          }
                      }
                      else if (listaStudents != null)
                      {
                          ICollection<Database.student> val = listaStudents[cis[i].Nome];
                          IEnumerator<Database.student> e1 = val.GetEnumerator();
                          while (e1.MoveNext())
                          {
                              tmp += " \n" + (++contador) + "." + name(e1.Current.person.personName);
                          }
                      }

                      dr[cis[i].DayOfWeek] = tmp;
                     // 
                  }
                   

            }
          
            GridView1.DataSource = dt;
          
            
            GridView1.Update();

          
        }

        private void salvarPessoaBut_Click(object sender, EventArgs e)
        {
            ExportToPdf(dt);
        }
        Bitmap memoryImage;
        private void CaptureScreen()
        {
            this.BackColor = Color.White;
            Color tmp = this.GridView1.BackgroundColor;
            this.GridView1.BackgroundColor = Color.White;
            Graphics myGraphics = this.GridView1.CreateGraphics();
            Size s = this.GridView1.Size;
            memoryImage = new Bitmap(s.Width, s.Height, myGraphics);
            Graphics memoryGraphics = Graphics.FromImage(memoryImage);
            memoryGraphics.CopyFromScreen(this.GridView1.Location.X, this.GridView1.Location.Y, 0, 0, s);
            this.GridView1.BackgroundColor = tmp;
        }

        private void printDocument1_PrintPage(System.Object sender,
               System.Drawing.Printing.PrintPageEventArgs e)
        {
            e.Graphics.DrawImage(memoryImage, 0, 0);
        }

        private PrintDocument printDocument1 = new PrintDocument();
        private void ExportToPdf(DataTable dt)
        {
            CaptureScreen();
            printDocument1.Print();
            

            ////PrintFormPdfData();
            //Process pdfProcess = new Process();
            //pdfProcess.StartInfo = new ProcessStartInfo()
            //{
            //    FileName = @"Horarios Imprimidos\" + nomeCalend + ".pdf",
            //    CreateNoWindow = true,
            //    Verb = "print",
            //};
            //pdfProcess.Start();

            //string printer = "Brother DCP-7010 USB Printer";
            //using (PrintDialog printDialog1 = new PrintDialog())
            //{
            //    printDialog1.PrinterSettings.PrinterName = printer;
            //    if (printDialog1.ShowDialog() == DialogResult.OK)
            //    {
            //        System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(@"Horarios Imprimidos\" + nomeCalend + ".pdf");
            //        //info.Arguments = “\”" + printDialog1.PrinterSettings.PrinterName + “\”";
            //        info.Arguments = "\"" + printer + "\"";
            //        info.CreateNoWindow = true;
            //        info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            //        info.UseShellExecute = true;
            //        info.Verb = "PrintTo";
            //        System.Diagnostics.Process.Start(info);
            //    }
            //}
        }

        private void PrintFormPdfData(string tempFile)
        {
           
            try
            {
                string gsArguments;
                string gsLocation;
                ProcessStartInfo gsProcessInfo;
                Process gsProcess;
                gsArguments = string.Format("-grey -noquery -printer \"HP LaserJet 5M\" \"{0}\"", tempFile);
                gsLocation = @"C:\Program Files\Ghostgum\gsview\gsprint.exe";
                gsProcessInfo = new ProcessStartInfo();
                gsProcessInfo.WindowStyle = ProcessWindowStyle.Hidden;
                gsProcessInfo.FileName = gsLocation;
                gsProcessInfo.Arguments = gsArguments;
                gsProcess = Process.Start(gsProcessInfo);
                gsProcess.WaitForExit();
            }
            finally
            {
                File.Delete(tempFile);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            String path1 = (@"Horarios Imprimidos\" + nomeCalend + ".pdf");
            String fullPath = Path.GetFullPath(path1);
            Document document = new Document();
            try
            {
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(path1, FileMode.Create));
            }
            catch (IOException) {
                Library.Utils.errorFields("O PDF "+nomeCalend+" encontra-se aberto. Feche-o e tente outra vez.","Feche o PDF");
                return;
            }
            document.Open();
            iTextSharp.text.Font font15 = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 15);
            iTextSharp.text.Font font11 = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 6);
            document.Add(new Phrase(this.Text.Replace("[Software de Gestão]", ""), iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 17)));
            PdfPTable table = new PdfPTable(dt.Columns.Count);
            PdfPRow row = null;
            float[] widths = new float[] { 4f, 4f, 4f, 4f, 4f, 4f, 4f };

            table.SetWidths(widths);

            table.WidthPercentage = 100;

            PdfPCell cell = new PdfPCell(new Phrase("Products"));

            cell.Colspan = dt.Columns.Count;
            dt.DefaultView.Sort = "Horas asc";
            foreach (DataColumn c in dt.Columns)
            {

                table.AddCell(new Phrase(c.ColumnName, font15));
            }

            foreach (DataRow r in dt.Rows)
            {
                if (dt.Rows.Count > 0)
                {
                    table.AddCell(new Phrase(r[0].ToString(), font11));
                    table.AddCell(new Phrase(r[1].ToString(), font11));
                    table.AddCell(new Phrase(r[2].ToString(), font11));
                    table.AddCell(new Phrase(r[3].ToString(), font11));
                    table.AddCell(new Phrase(r[4].ToString(), font11));
                    table.AddCell(new Phrase(r[5].ToString(), font11));
                    table.AddCell(new Phrase(r[6].ToString(), font11));
                }
            } document.Add(table);
            
            document.Close();
            Process.Start(fullPath);
        }

        private string name(string namePerson) {

            string[] words = namePerson.Split(' ');
            string nameToPass;
            if (words.Count() == 1)
            {
                nameToPass = words[0];
            }
            else {
                nameToPass = words[0]+" "+words[words.Count() - 1];
            }
            return nameToPass;
        }

    }
}
